import base64
import urllib
import requests
import json

API_KEY = "1nfG1U111TWUVBCwRrzu9tNB"
SECRET_KEY = "nNKXfgGfU8qemuC7PzOTGmODhOb90guQ"

def get_func():
    
    url = "https://vop.baidu.com/server_api"
    
    # speech 可以通过 get_file_content_as_base64("C:\fakepath\test.wav",False) 方法获取

    # speech = get_file_content_as_base64('./templates/test.wav', False),
    # length = len(speech)

    with open("./templates/test.wav", 'rb') as speech_file:
        speech_data = speech_file.read()
    length = len(speech_data)
    speech = get_file_content_as_base64("./templates/test.wav", False),
    # print(type(speech))
    # print(length,"_")
    # speech = str(speech, 'utf-8')
    # print(speech)
    payload = json.dumps({
        "format": "pcm",
        "rate": 16000,
        "channel": 1,
        "cuid": "32891787",
        "token": get_access_token(),
        "speech": speech[0],
        "len": length
    })
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    # return "111"
    return response.text
    # print(response.text,"111")
    

def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded 
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content

def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))
# if __name__ == "__main__":
#     main()